from django.core.cache import cache
from django.contrib.auth.forms import UserCreationForm
from django.views.generic.simple import direct_to_template
from django.http import HttpResponseRedirect
from django.views.generic.simple import direct_to_template
from django.utils import simplejson
from django.http import HttpResponseRedirect, HttpResponse

from google.appengine.api import mail

from contact.contact_form import ContactForm

import logging

def processForm( form ):
    logging.debug('process form...')
    # Validate the form:
    clean = form.is_valid()
    # Make some dicts to get passed back to the browser
    rdict = {'bad':'false'}
    if not clean:
        logging.debug('not clean...')
        rdict.update({'bad':'true'})
        d={}
        # This was painful, but I can't find a better way to extract the error messages:
        for field, err_msg in form.errors.iteritems():
            m = unicode(err_msg)
            s = m[ m.find("<li>") + 4 : m.find("</li>")]
            d.update({field:unicode(s)})
        # Bung all that into the dict
        rdict.update({'errs': d  })
    else:
        logging.debug('clean...')
        subject    = form.cleaned_data['subject']
        message    = form.cleaned_data['message']  
        sender     = form.cleaned_data['sender']
        cc_myself  = form.cleaned_data['cc_myself']
        recipients = ['algos.tccdolor@urv.cat']
        if cc_myself:
            recipients.append(sender)
        message = 'From: ' + sender + "\n" + message
        try:
            logging.debug('send message...')
            mail.send_mail('algos.urv@gmail.com', recipients, subject, message)
        except mail.Error, msg:
            logging.error('error email: ' + msg)
    logging.debug('message sent...')
    json = simplejson.dumps(rdict, ensure_ascii=False)
    # And send it off.
    logging.debug('return process form...' + json)
    return HttpResponse(json, mimetype='application/javascript')

# The main view:
def contactForm( request):
    # Is this a POST?
    if request.method == "POST":
        return processForm( ContactForm(request.POST) )
    else:
        return direct_to_template(request, 'contact/contact_form.html')
    